package com.demo.utils;

import org.apache.logging.log4j.Logger;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class WeChatUtils {
    private static final String WECHAT_WEBHOOK;
    private static final Logger log = LogUtils.getLogger();

    static {
        Properties props = new Properties();
        try (InputStream is = WeChatUtils.class.getClassLoader().getResourceAsStream("wechat.properties")) {
            if (is == null) {
                log.error("【WeChatUtils】错误: wechat.properties 文件未找到！");
                throw new RuntimeException("wechat.properties 文件未找到");
            }
            props.load(is);
            WECHAT_WEBHOOK = props.getProperty("wechat.webhook.key");
            log.info("【WeChatUtils】加载的 Webhook URL: " + WECHAT_WEBHOOK);
        } catch (Exception e) {
            log.error("【WeChatUtils】加载配置失败: " + e.getMessage());
            throw new RuntimeException("加载企业微信配置失败", e);
        }
    }

    public static void sendWeChatMessage(String message) {
        if (WECHAT_WEBHOOK == null || WECHAT_WEBHOOK.isEmpty()) {
            log.error("【WeChatUtils】错误: Webhook URL 未配置！");
            return;
        }

        log.info("【WeChatUtils】准备发送消息: " + message);

        try {
            String jsonBody = String.format(
                    "{\"msgtype\": \"markdown\", \"markdown\": {\"content\": \"%s\"}}",
                    message.replace("\n", "\\n")
            );

            URL url = new URL(WECHAT_WEBHOOK);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");

            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                log.error("【WeChatUtils】推送失败，HTTP 状态码: " + responseCode);
                log.error("【WeChatUtils】响应内容: " + conn.getResponseMessage());
            } else {
                log.info("【WeChatUtils】消息推送成功");
            }
        } catch (Exception e) {
            log.error("【WeChatUtils】推送异常: " + e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
        }
    }
}